package com.hyt.it.ogt.kq.service.gov.job;

import com.hyt.it.ogt.kq.service.gov.model.dto.CandidateCountDTO;
import com.hyt.it.ogt.kq.service.gov.model.entity.Task;
import com.hyt.it.ogt.kq.service.gov.service.ICandidateService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统计考务任务考生数量
 * 
 * @author huangwu
 * @since 2022-10-14
 */
@Component
@Slf4j
public class StatisticsTaskCandidateCountJob {

	@Resource
	private ITaskService taskService;

	@Resource
	private ICandidateService candidateService;

	/**
	 * 统计考试任务考生数量
	 */
	@XxlJob("statisticsTaskCandidateCountJob")
	public ReturnT<String> testJob() throws Exception {
		// 获取配置参数
		log.info("执行统计考试任务考生数量任务");
		String xxlparam = XxlJobHelper.getJobParam(); // 执行参数
		Integer size = 1000;
		if (StringUtils.isNotEmpty(xxlparam)) {
			size = Integer.valueOf(xxlparam);
		}
		List<Task> tasks = taskService.getTaskListLimit(size);
		Map<String, Integer> taskCountMap = new HashMap<>();
		if (!CollectionUtils.isEmpty(tasks)) {
			List<String> taskIds = tasks.stream().map(Task::getId).collect(Collectors.toList());
			// 获取数量
			List<CandidateCountDTO> candidateCounts = candidateService.getTaskCandidateCountByTaskids(taskIds);
			for (CandidateCountDTO candidateCount : candidateCounts) {
				taskCountMap.put(candidateCount.getTaskId(), candidateCount.getCandidateCount());
			}
			for (Task task : tasks) {
				task.setCandidateCount(taskCountMap.get(task.getId()));
			}
			taskService.updateBatchById(tasks);
		}

		log.info("执行统计考试任务考生数量任务结束");
		return ReturnT.SUCCESS;
	}
}
